﻿$(function () {
    layui.use(['element', 'notice', 'layer', 'treeTable', 'iziToast', 'numberInput'], function () {
        var layer = layui.layer,
            element = layui.element,
            table = layui.treeTable,
            notice = Util.notice !== null && Util.notice() !== null
                ? Util.notice() : layui.notice,
            iziToast = layui.iziToast,
            numberInput = layui.numberInput;
        var columntreetableconfig = {
            elem: '#columnmanagetable',
            tree: {
                iconIndex: 1,  // 折叠图标显示在第几列
                idName: 'id',  // 自定义id字段的名称
                pidName: 'pid'  // 自定义标识是否还有子节点的字段名称
            },
            cols: [
                { field: 'id', title: 'ID', width: 30 },
                { field: 'title', title: '栏目名称' },
                { field: 'language', title: '语言', width: 100 },
                //{ field: 'level', title: '深度', width: 120 },
                { field: 'layouttype', title: '布局类型', width: 100 },
                { field: 'layoutlisttemplate', title: '列表布局模板', width: 120 },
                { field: 'layoutdetailtemplate', title: '详情页布局模板', width: 120 },
                { field: 'url', title: '导航地址' },
                { field: 'displayorder', title: '排序', width: 65, align: "center", templet: '#displayorderTpl' },
                { title: '操作', minWidth: 100, templet: '#tableitemBars', fixed: "right", align: "center", singleLine: false }
            ],
            data: null
        },
            lodash = _,
            numInputIns = null,
            columnTableTreeIns = null;
        let initColumnTreeTable = function () {
            httpapi.fetchGet('/api/backend/business/columnmanage/getcolumntree?languageid=0&layout=true').then(res => {
                if (!httpapi.checkResponse(res))
                    //输入信息校验错误
                    notice.error(res.message);
                else {//Success
                    columntreetableconfig.data = res.data;
                    if (columnTableTreeIns === null)
                        columnTableTreeIns = table.render(columntreetableconfig);
                    else columnTableTreeIns.reload(columntreetableconfig);
                    columnTableTreeIns.expandAll();
                }
            }).catch(error => notice.error("对不起，出现未知错误，请您联系系统管理员！"));
        };
        initColumnTreeTable();

        //监听表格数据行按钮
        let editurl = "/business/columnmanage/edit",
            editWidowConfig = {
                title: "编辑/修改",
                type: 2,
                content: "",
                fixtolayoutbody: true,
                anim: 3,
                end: function () {
                    initColumnTreeTable();
                }
            },
            currentSystemModuleId = $("#currentSystemModuleId").val();
        //url: int Id of newsItemId
        //datas: object for api parameters 
        //callback: function
        var updateTableRow = function (url, datas, callback) {
            if (!lodash.isObject(datas) && !lodash.isEmpty(datas))
                return false;
            var index = layer.load(2, { time: 10 * 1000 });
            httpapi.fetchGet(url, datas).then(res => {
                layer.close(index);
                if (!httpapi.checkResponse(res)) {
                    //输入信息校验错误
                    notice.error(res.message);
                }
                else {//Success
                    if (lodash.isFunction(callback)) {
                        callback(res.message, res.data);
                    }
                }
            }).catch(error => consol.error(error));
        };
        table.on('tool(columnmanagetable)', function (obj) {
            var data = obj.data,
                thisElem = this,
                buttonid = layui.$(thisElem).data("buttonid");
            if (obj.event === 'Edit') {
                editWidowConfig.content = editurl + "?moduleid=" + currentSystemModuleId + "&buttonid=" + buttonid + "&columnid=" + data.id;
                Util.OpenMainWindow(editWidowConfig);
            } else if (obj.event === 'Delete') {
                layer.confirm("确定要进行删除操作吗？", function (confirmIndex) {
                    layer.close(confirmIndex);
                    iziToast.loading("删除中，请稍候...");
                    let node = new Object(DeleteNodeModel);
                    node.EntityId = data.id;
                    node.ButtonId = buttonid;
                    node.ModuleId = currentSystemModuleId;
                    $.deleteJSON("/api/backend/business/columnmanage/delete", node, function (res) {
                        iziToast.destroy();
                        if (!httpapi.checkResponse(res)) {
                            //输入信息校验错误
                            notice.error(res.message);
                        } else {//Success
                            notice.success(res.message);
                            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                        }
                    });
                });
            }
        });
        // 监听单元格单击事件
        //TreeTable不同于layui.table，无法监听到tool(filter) event事件
        table.on('cell(columnmanagetable)', function (obj) {
            if (obj.field === 'displayorder') {
                var data = obj.data;
                layer.open({
                    type: 1
                    , title: '设置排序'
                    , content: document.getElementById("displayorderInputTpl").innerHTML
                    , resize: false
                    , success: function (layero, index) {
                        var options = {
                            step: 1,
                            min: 1,
                            max: 150
                        };
                        if (numInputIns === null)
                            numInputIns = numberInput.render(options);
                        else numInputIns.reload(options);

                        numInputIns.setInitNumber(data.displayorder);
                    }
                    , btn: ['确定']
                    , yes: function (index, layero) {
                        var newsetVal = numInputIns.getCurrentNumber();
                        if (Util.isNumber(newsetVal)) {
                            updateTableRow('/api/backend/business/columnmanage/setorder', { columnid: data.id, order: newsetVal }, function (msg, neworder) {
                                if (msg.length > 0)
                                    notice.success(msg);
                                obj.update({
                                    displayorder: neworder//res.data
                                });
                            });
                        } else {
                            notice.error("请输入正确数值");
                            if (columnTableTreeIns === null)
                                columnTableTreeIns = table.render(columntreetableconfig);
                            else columnTableTreeIns.reload(columntreetableconfig);
                            columnTableTreeIns.expandAll();
                        }
                        layer.close(index);
                    }
                });
            }
        });
        //监听顶部按钮栏
        var PageButtonEvent = {
            Add: function (buttonid) {
                editWidowConfig.content = editurl + "?moduleid=" + currentSystemModuleId + "&buttonid=" + buttonid;
                Util.OpenMainWindow(editWidowConfig);
                return false;
            }
        };
        $('.pagebuttongroup .layui-btn').on('click', function (e) {
            e.preventDefault();
            var type = $(this).data('type');
            var buttonid = $(this).data("buttonid");
            PageButtonEvent[type] ? PageButtonEvent[type].call(this, buttonid) : '';
        });
    });//layui.use([
}); //$(function () {